<?php
/**
 * Created by PhpStorm.
 * User: youlognit
 * Date: 2021-09-09
 * Time: 20:38
 */
namespace App\Admin\Forms;

use App\Models\ChannelConfig;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;

class ZengJian extends Form implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能

    // 处理请求
    public function handle(array $input)
    {
        $names = [
            'yuzhi' => '阈值',
            'zengjianliang' => '增减量',
        ];
        try {
            foreach($input as $key => $item){
                $query = ChannelConfig::query();
                $obj = $query->where('key', $key)->first();
                if($obj){
                    $obj->value = $item;
                    $obj->save();
                }else{
                    $query->insert([
                        'name'          => $names[$key],
                        'key'           => $key,
                        'value'         => $item,
                        'created_at'    => date('Y-m-d H:i:s'),
                    ]);
                }
            }

            return $this->response()->success('添加成功')->redirect('/channel-report');
        }catch(\Exception $e){
            // 打印错误
            return $this->response()->success('添加失败');
        }
    }

    public function form()
    {
        // 获取外部传递参数
        //$id = $this->payload['id'] ?? null;

        $this->number('yuzhi', '阈值')->default(0)->required();
        // 密码确认表单
        $this->number('zengjianliang', '增/减量')->required();
    }

    // 返回表单数据，如不需要可以删除此方法
    public function default()
    {
        return [
            'yuzhi'         => '',
            'zengjianliang' => '',
        ];
    }
}
